import os  
import json  
import random  
import string

from PySide6.QtWidgets import QWidget,QFileDialog
from PySide6.QtCore import Slot
from ui.main_window_ui import Ui_Form

class MainWindow(QWidget):

    def __init__(self):
        #动态导入ui界面
        # self.ui = QUiLoader().load('ui/main_window.ui')
        
        super(MainWindow, self).__init__()
        
        self._ui = Ui_Form()
        self._ui.setupUi(self)

        self._init_event()
  
    def _init_event(self) -> None:
        self._ui.pushButton_select.clicked.connect(self._on_clicked_button_select)
        self._ui.pushButton_rename.clicked.connect(self._on_clicked_button_rename)
        self._ui.pushButton_back.clicked.connect(self._on_clicked_button_back)

    @Slot()
    def _on_clicked_button_select(self) -> None:      
        #选择目录，返回选中的路径
        FileDialog = QFileDialog(self)
        self._ui.label_directory.setText(FileDialog.getExistingDirectory(self, "标题"))
        pass

    @Slot()
    def _on_clicked_button_rename(self) -> None:
        directory = self._ui.label_directory.text()
        self._rename_files_and_save_mapping(directory)
        pass

    @Slot()
    def _on_clicked_button_back(self) -> None:
        directory = self._ui.label_directory.text()
        self._restore_filenames(directory)
        pass

    def _generate_random_name(self, length=32):
        """ 生成一个随机的乱码文件名 """
        letters = string.ascii_letters + string.digits
        return ''.join(random.choice(letters) for i in range(length))
    
    def _rename_files_and_save_mapping(self, directory, mapping_file='mapping.json'):
        """
        遍历文件夹，重命名所有文件并保存映射关系。
        :param directory: 要处理的文件夹路径
        :param mapping_file: 映射文件保存路径
        """
        
        with open(mapping_file, 'r') as f:  
            mapping = json.load(f)

        if mapping.get(directory) != None:
            print(f"已经重命名过")
            return

        mapping[directory] = {}

        for root, dirs, files in os.walk(directory):  
            for file in files:  
                old_path = os.path.join(root, file)  
                new_name = self._generate_random_name()
                new_path = os.path.join(root, new_name)  
                os.rename(old_path, new_path)
                mapping[directory][new_name] = file
                print(f'Rename: {file} -> {new_name}')
    
        with open(mapping_file, 'w') as f:  
            json.dump(mapping, f, indent=4)  
    
        print(f"文件重命名完成，映射已保存到 {mapping_file}")

    def _restore_filenames(self, directory, mapping_file='mapping.json'):  
        """  
        根据映射文件还原文件名。  
        :param directory: 要处理的文件夹路径  
        :param mapping_file: 映射文件路径  
        """  
        with open(mapping_file, 'r') as f:  
            mapping = json.load(f)
        
        if mapping.get(directory) == None:
            mapping[directory] = {}
    
        for root, dirs, files in os.walk(directory):  
            for file in files:  
                if file in mapping[directory]:
                    old_name = mapping[directory][file]
                    old_path = os.path.join(root, file)
                    new_path = os.path.join(root, old_name)
                    os.rename(old_path, new_path)
                    print(f'Back: {file} -> {old_name}')
        
        mapping.pop(directory)

        with open(mapping_file, 'w') as f:  
            json.dump(mapping, f, indent=4)  
    
        print("文件名已还原")